
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>许愿对对碰</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
      .card {
          transition: all 0.3s ease;
          transform-style: preserve-3d;
      }
      .card.selected {
          transform: scale(1.05);
          box-shadow: 0 0 15px rgba(255, 215, 0, 0.7);
      }
      .card.matched {
          animation: fadeOut 0.5s forwards;
      }
      @keyframes fadeOut {
          to { opacity: 0; transform: scale(0.8); }
      }
      .reward-btn {
          transition: all 0.2s ease;
      }
      .reward-btn:hover {
          transform: translateY(-3px);
      }
  </style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-purple-50 min-h-screen">
<div class="container mx-auto px-4 py-8">
  <!-- 游戏标题 -->
  <header class="text-center mb-8">
    <h1 class="text-4xl font-bold text-purple-800 mb-2">许愿对对碰</h1>
    <p class="text-gray-600">消除相同卡牌，收集更多奖励！</p>
  </header>

  <!-- 游戏主区域 -->
  <div class="max-w-3xl mx-auto bg-white rounded-xl shadow-lg overflow-hidden p-6">
    <!-- 游戏信息面板 -->
    <div class="flex justify-between items-center mb-6">
      <div class="bg-purple-100 px-4 py-2 rounded-lg">
        <span class="font-semibold text-purple-800">碰数: </span>
        <span id="match-count" class="text-2xl font-bold">0</span>
      </div>
      <div id="reward-pool" class="bg-yellow-100 px-4 py-2 rounded-lg cursor-pointer reward-btn">
        <span class="font-semibold text-yellow-800">奖励卡池: </span>
        <span id="reward-count" class="text-2xl font-bold">0</span>
        <i class="fas fa-gift ml-2 text-yellow-600"></i>
      </div>
    </div>

    <!-- 许愿选择区域 -->
    <div id="wish-selection" class="mb-8 text-center">
      <h2 class="text-xl font-semibold text-gray-700 mb-4">请选择你的许愿卡牌</h2>
      <div class="grid grid-cols-3 gap-4 mb-8 min-h-[200px]">
        <!-- 许愿卡牌选项将通过JS动态生成 -->
      </div>
    </div>
    <!-- 支付区域 -->
    <div id="game-payment" class="grid gap-4 mb-8 min-h-[200px]" style="display: flex; justify-content: space-around;">
      <div style="width: 400px">
      <img src="./img/1.jpg" alt="图片1" class="w-full h-full object-cover">
      </div>

    </div>

    <!-- 游戏区域 -->
    <div id="game-area" class="grid grid-cols-3 gap-4 mb-8 min-h-[200px]">
      <!-- 卡牌将通过JS动态生成 -->
      <div class="text-center py-10 text-gray-400" id="game-message">
        请先扫码支付开始游戏
      </div>

    </div>
    <div id="restartBtn" style="display: flex; justify-content: center; margin-top: 20px; margin-bottom: 20px">
      <button class="bg-white p-3 rounded-lg shadow-md cursor-pointer hover:bg-purple-50 transition-colors text-2xl" onclick="initGame()">重新开始</button>
    </div>
    <!-- 游戏规则 -->
    <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
      <h3 class="font-semibold text-gray-700 mb-2 flex items-center">
        <i class="fas fa-info-circle mr-2 text-blue-500"></i>游戏规则
      </h3>
      <ul class="text-sm text-gray-600 space-y-1">
        <li>• 选择1种卡面作为"许愿"卡牌</li>
        <li>• 初始发放9张卡牌，每出现1张许愿牌，奖励池+1张</li>
        <li>• 点击场上2张相同卡牌可消除（计为1次"碰"）</li>
        <li>• 点击奖励卡池可将卡牌放置到场上</li>
        <li>• 当场无相同卡牌且奖励池为空时游戏结束</li>
      </ul>
    </div>
  </div>
</div>

<script>
  // 游戏状态
  const gameState = {
    cardTypes: ['2', '3', '4', '5', '6', '7', '8', '9', '10'], // 9种卡面
    wishCard: null,
    deck: [],
    fieldCards: [],
    rewardPool: [],
    selectedCards: [],
    matchCount: 0,
    gameStarted: false
  };

  // DOM元素
  const elements = {
    wishSelection: document.getElementById('wish-selection'),
    payment: document.getElementById('game-payment'),
    gameArea: document.getElementById('game-area'),
    gameMessage: document.getElementById('game-message'),
    matchCount: document.getElementById('match-count'),
    rewardCount: document.getElementById('reward-count'),
    rewardPool: document.getElementById('reward-pool'),
    restartBtn: document.getElementById('restartBtn')
  };

  let count = 0

  // 初始化游戏
  function initGame() {
    count = 0
    elements.gameArea.classList.add('hidden');
    elements.wishSelection.classList.remove('hidden');
    elements.payment.style.display = 'flex';
    elements.restartBtn.style.display = 'none';
    // 生成卡牌库 (每种卡面6张)
    gameState.deck = [];
    for (let type of gameState.cardTypes) {
      for (let i = 0; i < 6; i++) {
        gameState.deck.push(type);
      }
    }
    shuffleDeck(gameState.deck);

    // 渲染许愿卡选择界面
    renderWishSelection();
  }

  // 渲染许愿卡选择界面
  function renderWishSelection() {
    const container = elements.wishSelection.querySelector('div');
    container.innerHTML = '';

    gameState.cardTypes.forEach(type => {
      const card = document.createElement('div');
      card.className = 'bg-white p-3 rounded-lg shadow-md cursor-pointer hover:bg-purple-50 transition-colors text-2xl';
      card.style.cssText = `
          background-image: url('./img/${type}.jpg');
          background-position: center;
          background-repeat: no-repeat;
          background-size: cover;
          height: 250px;
        `
      // card.textContent = type;
      card.onclick = () => selectWishCard(type);
      container.appendChild(card);
    });
  }

  // 选择许愿卡
  function selectWishCard(type) {
    gameState.wishCard = type;
    elements.wishSelection.classList.add('hidden');
    elements.gameArea.classList.remove('hidden');
    elements.payment.style.display = 'none';

    startGame();
  }

  // 开始游戏
  function startGame() {
    gameState.gameStarted = true;
    gameState.fieldCards = gameState.deck.splice(0, 9); // 初始9张牌
    gameState.matchCount = 0;
    gameState.selectedCards = [];

    // 计算奖励卡池数量
    const wishCount = gameState.fieldCards.filter(card => card === gameState.wishCard).length;
    gameState.rewardPool = gameState.deck.splice(0, wishCount);

    updateUI();
    checkInitialGameOver();
  }

  // 检查初始游戏是否结束
  function checkInitialGameOver() {
    const hasDuplicates = new Set(gameState.fieldCards).size !== gameState.fieldCards.length;
    if (!hasDuplicates && gameState.rewardPool.length === 0) {
      endGame();
    }
  }

  // 洗牌
  function shuffleDeck(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
  }

  // 渲染游戏区域
  function renderGameArea() {
    elements.gameArea.innerHTML = '';

    if (gameState.fieldCards.length === 0) {
      const emptyMsg = document.createElement('div');
      emptyMsg.className = 'col-span-3 text-center py-10 text-gray-400';
      emptyMsg.textContent = '场上没有卡牌，请从奖励池抽取';
      elements.gameArea.appendChild(emptyMsg);
      return;
    }

    gameState.fieldCards.forEach((card, index) => {
      const cardElement = document.createElement('div');
      cardElement.className = `card bg-white rounded-lg shadow-md p-4 text-center text-4xl cursor-pointer flex items-center justify-center ${
        gameState.selectedCards.includes(index) ? 'selected bg-yellow-100' : ''
      }`;
      // cardElement.textContent = card;
      cardElement.style.cssText = `
          background-image: url('./img/${card}.jpg');
          background-position: center;
          background-repeat: no-repeat;
          background-size: cover;
          height: 250px;
        `
      cardElement.onclick = () => selectFieldCard(index);
      elements.gameArea.appendChild(cardElement);
    });
  }

  // 选择场上卡牌
  function selectFieldCard(index) {
    if (!gameState.gameStarted) return;

    // 如果已经选中了这张卡，取消选择
    if (gameState.selectedCards.includes(index)) {
      gameState.selectedCards = gameState.selectedCards.filter(i => i !== index);
      renderGameArea();
      return;
    }

    // 如果已经选中了一张卡，尝试匹配
    if (gameState.selectedCards.length === 1) {
      const firstIndex = gameState.selectedCards[0];
      if (gameState.fieldCards[firstIndex] === gameState.fieldCards[index]) {
        // 匹配成功
        gameState.fieldCards = gameState.fieldCards.filter((_, i) => i !== firstIndex && i !== index);
        gameState.matchCount++;

        gameState.selectedCards = [];
        gameState.rewardPool.push(gameState.deck.pop());
        gameState.fieldCards.push(gameState.rewardPool.pop());

        // 检查是否需要添加奖励卡
        if (gameState.fieldCards[gameState.fieldCards.length - 1] === gameState.wishCard && gameState.deck.length > 0) {
          // gameState.rewardPool.push(gameState.deck.pop());
          gameState.rewardPool.push(gameState.deck.pop());
        }

        updateUI();
        checkGameOver();

        return;
      }
    }

    // 选中卡牌
    gameState.selectedCards.push(index);
    if (gameState.selectedCards.length > 2) {
      gameState.selectedCards.shift();
    }

    renderGameArea();
  }

  // 从奖励池抽取卡牌
  function drawFromRewardPool() {
    if (gameState.rewardPool.length > 0) {
      // 检查是否需要添加奖励卡
      // gameState.rewardPool.push(gameState.deck.pop());
      gameState.fieldCards.push(gameState.rewardPool.pop());
      if (gameState.fieldCards[gameState.fieldCards.length - 1] === gameState.wishCard ) {
        gameState.rewardPool.push(gameState.deck.pop());
      }
      updateUI();
      checkGameOver();
    }
  }

  // 更新UI
  function updateUI() {
    renderGameArea();
    elements.matchCount.textContent = gameState.matchCount;
    elements.rewardCount.textContent = gameState.rewardPool.length;
    if(elements.rewardCount.textContent > 0){
      count ++
    }

    if (gameState.rewardPool.length > 0) {
      elements.rewardPool.classList.remove('opacity-50');
      elements.rewardPool.classList.add('hover:bg-yellow-200');
    } else {
      elements.rewardPool.classList.add('opacity-50');
      elements.rewardPool.classList.remove('hover:bg-yellow-200');
    }
  }

  // 检查游戏是否结束
  function checkGameOver() {
    const hasDuplicates = new Set(gameState.fieldCards).size !== gameState.fieldCards.length;
    if (!hasDuplicates && gameState.rewardPool.length === 0) {
      endGame();
    }
  }

  // 游戏结束
  function endGame() {
    gameState.gameStarted = false;
    let message = `游戏结束！你的碰数是: ${gameState.matchCount} 奖品：`;

    if (gameState.matchCount === 0) {
      message += "  恭喜获得迪士尼挂件随机！（500积分）";
    } else if (gameState.matchCount === 1) {
      message += "  恭喜获得港迪万圣贝儿一枚~（300积分）";
    } else if (gameState.matchCount === 2) {
      message += "  恭喜获得港迪万圣雪莉玫一枚（200积分）";
    } else if (gameState.matchCount === 9) {
      message += "  刮刮乐";
    } else if (gameState.matchCount === 10) {
      message += "  30选7一次";
    } else if (gameState.matchCount === 11) {
      message += "  恭喜获得柿子olu（200积分）";
    } else if (gameState.matchCount === 12) {
      message += "  恭喜获得免费30选7两次";
    } else if (gameState.matchCount === 13) {
      message += "  恭喜获得黑皮哭娃（400积分）";
    } else if (gameState.matchCount >= 14) {
      message += "  呜呜呜，含泪亏1k软妹币！";
    } else if (gameState.matchCount >= 3 && gameState.matchCount <= 6) {
      message += "  恭喜获得0.5积分（十点积分换一次抽奖）！";
    } else {
      message += "  恭喜获得1积分（十点积分换一次抽奖）！";
    }
    if (count === 0){
      message += `\n没有许愿卡，赠送一次(禁止套娃！)`;
    }
    console.log(message)

    // 显示重新开始按钮
    // elements.restartBtn.style.display = 'flex';

    // const restartBtn = document.createElement('button');
    // restartBtn.className = 'mt-4 bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700 transition-colors';
    // restartBtn.textContent = '再来一局';
    // restartBtn.onclick = () => {
    //   elements.restartBtn.classList.add('hidden');
    //   initGame();
    // };

    // elements.gameMessage.innerHTML = message;
    // elements.restartBtn.classList.remove('hidden');
    // elements.restartBtn.appendChild(restartBtn);
    setTimeout(()=>{
      elements.restartBtn.style.display = 'flex';
      alert(message)

    }, 1000);

  }

  // 事件监听
  elements.rewardPool.addEventListener('click', drawFromRewardPool);

  // 初始化游戏
  initGame();
</script>
</body>
</html>
